<template>
  <li
    class="u-msg"
    :class="{
      'item-me': msg.flow==='out',
      'item-you': msg.flow==='in',
      'item-time': msg.type==='timeTag',
      'item-tip': msg.type==='tip',
      'session-chat': type==='session'
    }"
    v-show="msg.show"
  >
    <div v-if="msg.type==='timeTag'">---- {{msg.showText}} ----</div>
    <div v-else-if="msg.type==='tip'" class="tip">{{msg.showText}}</div>
    <div
      v-else-if="msg.flow==='in' || msg.flow==='out'"
      :idClient="msg.idClient"
      :time="msg.time"
      :flow="msg.flow"
      :type="msg.type"
    >
      <a class="msg-head" v-if="msg.type!=='custom'">
        <img class="icon u-circle" :src="msg.avatar||avatar" />
      </a>
      <span v-if="msg.type==='text'" class="msg-text" v-html="msg.showText"></span>
      <div v-if="msg.type==='custom'" class="msg-content">
        <p class="order" v-show="msg.content.show">
          {{$t('l.chat_message0')}}：{{msg.content.orderNo}}
          <span
            class="link"
            @click="linkTo(msg.content.orderNo)"
          >{{$t('l.chat_message1')}}></span>
        </p>
        <div class="orderMsg">
          <p class="desc">{{msg.content.showText}}</p>
          <p class="time">{{msg.content.showTime}}</p>
        </div>
      </div>
      <span
        v-else-if="msg.type==='image'"
        class="msg-text"
        ref="mediaMsg"
        @click.stop="showFullImg(msg.originLink)"
      ></span>
      <span v-if="msg.status==='fail'" class="msg-failed">
        <i class="weui-icon-warn"></i>
      </span>
    </div>
  </li>
</template>

<script>
import util from "@/utils";
import config from "@/configs";

export default {
  inject: ["reload"],
  props: {
    type: String, // 类型，chatroom, session
    rawMsg: {
      type: Object,
      default() {
        return {};
      }
    },
    userInfos: {
      type: Object,
      default() {
        return {};
      }
    },
    myInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    isHistory: {
      type: Boolean,
      default() {
        return false;
      }
    }
  },
  data() {
    const orderMsg = {
      601: this.$t("l.chat_message3"),
      602: this.$t("l.chat_message6"),
      603: this.$t("l.chat_message8"),
      604: this.$t("l.chat_message9"),
      605: this.$t("l.chat_message10"),
      606: this.$t("l.chat_message7"),
      607: this.$t("l.chat_message7"),
      608: this.$t("l.chat_message4"),
      609: this.$t("l.chat_message5"),
      610: this.$t("l.chat_message11"),
      611: this.$t("l.chat_message12"),
      612: this.$t("l.chat_message13"),
      613: this.$t("l.chat_message14"),
      614: this.$t("l.chat_message15"),
      615: this.$t("l.chat_message16"),
      616: this.$t("l.chat_message17")
    };
    return {
      msg: "",
      isFullImgShow: false,
      orderMsg: orderMsg
    };
  },
  watch: {
    rawMsg(newVal, oldVal) {
      let newCustom = newVal && newVal.localCustom;
      if (!newCustom || !newVal || newVal.type !== "audio") {
        return;
      }
      let oldCustom = oldVal && oldVal.localCustom;
      if (newCustom !== oldCustom) {
        this.computedItem();
      }
    }
  },
  beforeMount() {
    this.computedItem();
  },
  mounted() {
    let item = this.msg;
    // 有时序问题的操作
    this.$nextTick(() => {
      let media = null;
      if (item.type === "image") {
        // 图片消息缩略图
        media = new Image();
        media.src = item.file.url + "?imageView&thumbnail=180x0&quality=85";
      } else if (item.type === "custom-type1") {
        // 猜拳消息
      } else if (item.type === "custom-type3") {
        // 贴图表情
      }
      if (media) {
        if (this.$refs.mediaMsg) {
          this.$refs.mediaMsg.appendChild(media);
        }
        media.onload = () => {
          this.$emit("msg-loaded");
        };
        media.onerror = () => {
          this.$emit("msg-loaded");
        };
      } else {
        this.$emit("msg-loaded");
      }
    }); // end this.nextTick
  },
  methods: {
    computedItem() {
      let item = Object.assign({ show: true }, this.rawMsg);

      // 标记用户，区分聊天室、普通消息
      if (this.type === "session") {
        if (item.flow === "in") {
          if (item.from !== this.$store.state.im.userUID) {
            item.avatar =
              (this.userInfos[item.from] && this.userInfos[item.from].avatar) ||
              config.defaultUserIcon;
          } else {
            item.avatar = this.myInfo.avatar;
          }
        } else if (item.flow === "out") {
          item.avatar = this.myInfo.avatar;
        }
      }

      if (item.type === "timeTag") {
        // 标记发送的时间
        item.showText = item.text;
      } else if (item.type === "text") {
        // 文本消息
        item.showText = util.escape(item.text);
        if (/\[[^\]]+\]/.test(item.showText)) {
          // let emojiItems = item.showText.match(/\[[^\]]+\]/g)
          // emojiItems.forEach(text => {
          //   let emojiCnt = emojiObj.emojiList.emoji
          //   if (emojiCnt[text]) {
          //     item.showText = item.showText.replace(text, `<img class="emoji-small" src="${emojiCnt[text].img}">`)
          //   }
          // })
        }
      } else if (item.type === "image") {
        // 原始图片全屏显示
        item.originLink = item.file.url;
      } else if (item.type === "custom") {
        let content = {};

        item.show = item.from !== this.$store.state.im.userUID;

        try {
          content = JSON.parse(item.content);
          item.content = {
            show: Number(content.msg) <= 604,
            orderNo: content.orderNo,
            showText: this.orderMsg[content.msg],
            showTime: util.formatDate(item.time)
          };
        } catch (error) {
          item.show = false;
        }
      } else {
        item.showText = `[${util.mapMsgType(item)}]`;
      }
      this.msg = item;
    },
    showFullImg(src) {
      this.$store.dispatch("im/showFullscreenImg", {
        src
      });
    },
    linkTo(orderNo) {
      let routeOrderNo = this.$route.params.id;

      if (routeOrderNo === orderNo) {
        this.reload();
      } else {
        this.$router.push(`/orderDetail/${orderNo}`);
      }
    }
  }
};
</script>

<style lang="less" scoped>
.u-msg {
  /deep/.msg-text {
    min-height: 20px;
    font-size: 14px;
    font-familyA: PingFangSC-Regular;
    font-weight: 400;
    color: #fff;
    line-height: 20px;
    padding: 10px 20px;
    max-width: 45%;
    word-break: break-all;
    img {
      max-width: 100%;
    }
  }
  .msg-content {
    //float: right;
    font-size: 14px;
    font-familyA: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 56, 94, 1);
    text-align: center;
    //margin-right: 64px;
    padding-top: 20px;
    overflow: hidden;
    .link {
      margin-left: 20px;
      color: #2D8DFE;
      cursor: pointer;
    }
    .order {
      margin-bottom: 16px;
    }
    .orderMsg {
      //float: right;
      min-width: 196px;
      padding-right: 30px;
      text-align: center;
      .desc {
        // margin-right: 30px;
      }
      .time {
        text-align: center;
        //margin-right: 90px;
      }
    }
  }
  .u-circle {
    width: 36px;
    height: 36px;
    border-radius: 100%;
  }
  &.item-time {
    display: none;
  }
  &.session-chat {
    padding: 8px 23px 8px 30px;
    clear: both;
    overflow: hidden;
  }
  &.item-me {
    .msg-head {
      float: right;
      margin-left: 14px;
      margin-top: 2px;
    }
    .msg-text {
      float: right;
      background: #2D8DFE;
      border-radius: 9px 0 9px 9px;
    }
  }
  &.item-you {
    .msg-head {
      float: left;
      margin-right: 14px;
      margin-top: 2px;
    }
    .msg-text {
      float: left;
      background: #f2f6fa;
      border-radius: 0 9px 9px 9px;
      color: #333;
    }
  }
}
</style>
